package api

import (
	"gitee.com/alex_li/upload/internal/etc"
	"github.com/lishimeng/app-starter/server"
	"github.com/lishimeng/go-log"
	"io"
	"os"
	"path/filepath"
	"sync"
)

var (
	maxUploadSize int64
)

var once sync.Once

func initUploadSize() {
	var per = etc.Config.Upload.MaxSize
	if per == 0 {
		log.Info("use default max size 1MB")
		per = 1
	}
	log.Info("max size:%dMB", per)
	maxUploadSize = per * 1024 * 1024 // n MB
}

func upload(ctx server.Context) {

	once.Do(func() {
		initUploadSize()
	})
	log.Info("upload... max size: %d", maxUploadSize)
	ctx.C.SetMaxRequestBodySize(maxUploadSize)

	var resp UploadResponse
	file, info, err := ctx.C.FormFile("file")
	if err != nil {
		log.Info(err)
		resp.FileResponse.Success = false
		ctx.Json(resp)
		return
	}
	log.Info("file:%s", info.Filename)
	defer file.Close()
	fname := info.Filename

	subFile := handleName(fname)

	resp.Name = fname
	resp.File = subFile

	dest := etc.Config.Upload.Root + subFile
	out, err := os.OpenFile(dest,
		os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		log.Info("open file:%s error:%s", dest, err.Error())
		resp.Code = 500
		resp.FileResponse.Success = false
		ctx.Json(resp)
		return
	}
	defer out.Close()
	size, err := io.Copy(out, file)
	if err != nil {
		log.Debug(err)
		resp.Code = 500
		resp.FileResponse.Success = false
		ctx.Json(resp)
		return
	}

	log.Debug("upload file:%s -> %s[%d]", fname, dest, size)

	resp.Code = 200
	resp.FileResponse.Success = true
	ctx.Json(resp)
}

func handleName(src string) (fName string) {
	if !etc.Config.Upload.HashName {
		fName = src
		return
	}
	fName = genTmpFileName(src)
	if etc.Config.Upload.KeepExt {
		ext := filepath.Ext(src)
		fName = fName + ext
	}
	return
}
